import React, { useState, ReactNode } from 'react';
import { Card, Button, Space, message, Popconfirm, Drawer } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { SearchForm, DataTable, ModalForm, PageHeader, ExportImport } from '@/components';
import type { SearchFormItem, ModalFormItem } from '@/components';
import { useCrudList } from '@/hooks';
import type { FormMode } from '@/types';

// CRUD 操作处理器
export interface CrudActionHandlers<T = any> {
  onCreate: () => void;
  onEdit: (record: T) => void;
  onView: (record: T) => void;
  onDelete: (id: string) => void;
  onRefresh: () => void;
}

// CRUD 数据和状态
export interface CrudDataContext<T = any, P = any> {
  data: T[];
  loading: boolean;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  searchParams: P;
  refresh: () => void;
  fetchData: (params?: Partial<P & { page?: number; pageSize?: number }>) => Promise<void>;
}

// CrudPage 配置
export interface CrudPageProps<T = any, P = any> {
  // ========== 基础配置 ==========
  title: string;
  
  // ========== API 配置 ==========
  fetchApi: (params: P & { page: number; pageSize: number }) => Promise<any>;
  createApi?: (data: any) => Promise<any>;
  updateApi?: (data: any) => Promise<any>;
  deleteApi?: (id: string) => Promise<any>;
  batchDeleteApi?: (ids: string[]) => Promise<any>;
  
  // ========== 表格配置 ==========
  columns: ColumnsType<T> | ((handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ColumnsType<T>);
  rowKey?: string;
  scroll?: { x?: number; y?: number };
  
  // ========== 搜索配置 ==========
  searchItems?: SearchFormItem[];
  
  // ========== 表单配置 ==========
  formItems?: ModalFormItem[] | ((mode: FormMode, record?: T) => ModalFormItem[]);
  editFormItems?: ModalFormItem[] | ((mode: FormMode, record?: T) => ModalFormItem[]); // 编辑模式专用表单配置
  formTitle?: {
    create?: string;
    edit?: string;
    view?: string;
  };
  formWidth?: number;
  
  // ========== 数据转换函数 ==========
  transformBeforeSubmit?: (values: any) => any; // 提交前数据转换
  transformBeforeEdit?: (record: T) => any; // 编辑前数据转换
  
  // ========== 权限配置 ==========
  permissions?: {
    create?: boolean;
    update?: boolean;
    delete?: boolean;
  };
  
  // ========== 操作按钮配置 ==========
  showCreateButton?: boolean;
  createButtonText?: string;
  showEditButton?: boolean;
  editButtonText?: string;
  showViewButton?: boolean;
  viewButtonText?: string;
  showDeleteButton?: boolean;
  deleteButtonText?: string;
  
  // ========== 自定义操作列 ==========
  // 在标准编辑/删除按钮之前添加的操作
  renderExtraActions?: (record: T, handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ReactNode;
  // 完全自定义操作列（会覆盖默认的编辑/删除按钮）
  renderActions?: (record: T, handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ReactNode;
  // 是否显示默认的操作列
  showActionColumn?: boolean;
  actionColumnWidth?: number;
  
  // ========== 页面头部额外操作 ==========
  renderHeaderExtra?: (handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ReactNode;
  
  // ========== 批量操作配置 ==========
  enableBatchDelete?: boolean;
  batchDeleteButtonText?: string;
  
  // ========== 导入导出配置 ==========
  exportConfig?: {
    filename?: string;
    columns: Array<{ header: string; key: string; width?: number }>;
    sheetName?: string;
    onExport?: () => Promise<any[]>;
  };
  importConfig?: {
    onImport: (data: any[]) => Promise<void>;
    validate?: (data: any[]) => { valid: boolean; errors?: string[] };
    templateFilename?: string;
    templateColumns?: Array<{ header: string; key: string; width?: number }>;
    templateSampleData?: any[];
  };
  
  // ========== 详情抽屉配置 ==========
  detailDrawerTitle?: string;
  detailDrawerWidth?: number;
  renderDetailContent?: (record: T, handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ReactNode;
  
  // ========== 自定义弹窗/内容 ==========
  // 在页面底部渲染额外的内容（如自定义弹窗）
  children?: (handlers: CrudActionHandlers<T>, context: CrudDataContext<T, P>) => ReactNode;
  
  // ========== 生命周期钩子 ==========
  onCreateBefore?: () => boolean | Promise<boolean>;
  onEditBefore?: (record: T) => boolean | Promise<boolean>;
  onViewBefore?: (record: T) => boolean | Promise<boolean>;
  onDeleteBefore?: (record: T) => boolean | Promise<boolean>;
  onFormSubmitBefore?: (values: any, mode: FormMode, record?: T) => any | Promise<any>;
  onFormSubmitAfter?: (values: any, mode: FormMode, record?: T) => void | Promise<void>;
  onDeleteAfter?: (record: T) => void | Promise<void>;
  
  // ========== 其他配置 ==========
  initialPageSize?: number;
  deleteConfirmTitle?: string | ((record: T) => string);
}

export function CrudPage<T extends Record<string, any> = any, P extends Record<string, any> = any>(
  props: CrudPageProps<T, P>
) {
  const {
    title,
    fetchApi,
    createApi,
    updateApi,
    deleteApi,
    batchDeleteApi,
    columns,
    rowKey = 'id',
    scroll,
    searchItems,
    formItems,
    editFormItems,
    formTitle = { create: '新增', edit: '编辑', view: '查看' },
    formWidth = 600,
    transformBeforeSubmit,
    transformBeforeEdit,
    permissions = { create: true, update: true, delete: true },
    showCreateButton = true,
    createButtonText = '新增',
    showEditButton = true,
    editButtonText = '编辑',
    showViewButton = false,
    viewButtonText = '查看',
    showDeleteButton = true,
    deleteButtonText = '删除',
    enableBatchDelete = false,
    batchDeleteButtonText = '批量删除',
    exportConfig,
    importConfig,
    detailDrawerTitle = '详情',
    detailDrawerWidth = 600,
    renderDetailContent,
    renderExtraActions,
    renderActions,
    showActionColumn = true,
    actionColumnWidth = 200,
    renderHeaderExtra,
    children,
    onCreateBefore,
    onEditBefore,
    onViewBefore,
    onDeleteBefore,
    onFormSubmitBefore,
    onFormSubmitAfter,
    onDeleteAfter,
    initialPageSize = 20,
    deleteConfirmTitle = '确定要删除吗？',
  } = props;

  // 表单状态
  const [formVisible, setFormVisible] = useState(false);
  const [formMode, setFormMode] = useState<FormMode>('create');
  const [currentRecord, setCurrentRecord] = useState<T | undefined>();
  
  // 详情抽屉状态
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [detailRecord, setDetailRecord] = useState<T | undefined>();
  
  // 批量选择状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<T[]>([]);

  // 使用 CRUD Hook
  const {
    data,
    loading,
    pagination,
    searchParams,
    handleSearch,
    handleReset,
    handlePageChange,
    refresh,
    fetchData,
  } = useCrudList<T, P>({
    fetchApi,
    initialPageSize,
  });

  // 数据上下文
  const context: CrudDataContext<T, P> = {
    data,
    loading,
    pagination,
    searchParams,
    refresh,
    fetchData,
  };

  // ========== CRUD 操作 ==========
  
  // 新增
  const handleCreate = async () => {
    if (onCreateBefore) {
      const canCreate = await onCreateBefore();
      if (!canCreate) return;
    }
    setFormMode('create');
    setCurrentRecord(undefined);
    setFormVisible(true);
  };

  // 编辑
  const handleEdit = async (record: T) => {
    if (onEditBefore) {
      const canEdit = await onEditBefore(record);
      if (!canEdit) return;
    }
    setFormMode('edit');
    // 如果有 transformBeforeEdit 函数，则先转换数据
    const editData = transformBeforeEdit ? transformBeforeEdit(record) : record;
    setCurrentRecord(editData);
    setFormVisible(true);
  };

  // 查看详情
  const handleView = async (record: T) => {
    if (onViewBefore) {
      const canView = await onViewBefore(record);
      if (!canView) return;
    }
    setDetailRecord(record);
    setDetailDrawerVisible(true);
  };

  // 删除
  const handleDelete = async (id: string) => {
    if (!deleteApi) {
      message.warning('未配置删除接口');
      return;
    }

    const record = data.find(item => (item as any)[rowKey] === id);
    if (!record) return;

    if (onDeleteBefore) {
      const canDelete = await onDeleteBefore(record);
      if (!canDelete) return;
    }

    try {
      await deleteApi(id);
      message.success('删除成功');
      refresh();
      
      if (onDeleteAfter) {
        await onDeleteAfter(record);
      }
    } catch (error: any) {
      // 错误已在拦截器中处理
      console.error('Delete failed:', error);
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (!batchDeleteApi) {
      message.warning('未配置批量删除接口');
      return;
    }

    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }

    try {
      await batchDeleteApi(selectedRowKeys as string[]);
      message.success(`成功删除 ${selectedRowKeys.length} 条数据`);
      setSelectedRowKeys([]);
      setSelectedRows([]);
      refresh();
    } catch (error: any) {
      console.error('Batch delete failed:', error);
    }
  };

  // 表单提交
  const handleFormSubmit = async (values: any) => {
    try {
      let submitData = values;
      
      // 数据转换（transformBeforeSubmit）
      if (transformBeforeSubmit) {
        submitData = transformBeforeSubmit(values);
      }
      
      // 提交前处理（onFormSubmitBefore）
      if (onFormSubmitBefore) {
        submitData = await onFormSubmitBefore(submitData, formMode, currentRecord);
      }

      if (formMode === 'create') {
        if (!createApi) {
          message.warning('未配置创建接口');
          return;
        }
        await createApi(submitData);
        message.success('创建成功');
      } else {
        if (!updateApi) {
          message.warning('未配置更新接口');
          return;
        }
        await updateApi({ ...submitData, id: (currentRecord as any)[rowKey] });
        message.success('更新成功');
      }

      setFormVisible(false);
      refresh();

      // 提交后处理
      if (onFormSubmitAfter) {
        await onFormSubmitAfter(values, formMode, currentRecord);
      }
    } catch (error: any) {
      // 错误已在拦截器中处理
      console.error('Submit failed:', error);
    }
  };

  // Action handlers
  const handlers: CrudActionHandlers<T> = {
    onCreate: handleCreate,
    onEdit: handleEdit,
    onView: handleView,
    onDelete: handleDelete,
    onRefresh: refresh,
  };

  // ========== 构建表格列 ==========
  
  // 默认操作列
  const defaultActionColumn: ColumnsType<T>[0] = {
    title: '操作',
    key: 'action',
    width: actionColumnWidth,
    fixed: 'right',
    render: (_, record) => (
      <Space size="small">
        {/* 额外的自定义操作 */}
        {renderExtraActions && renderExtraActions(record, handlers, context)}
        
        {/* 自定义操作（会覆盖默认按钮） */}
        {renderActions ? (
          renderActions(record, handlers, context)
        ) : (
          <>
            {/* 默认查看按钮 */}
            {showViewButton && (
              <Button
                type="link"
                size="small"
                icon={<EyeOutlined />}
                onClick={() => handleView(record)}
              >
                {viewButtonText}
              </Button>
            )}
            
            {/* 默认编辑按钮 */}
            {showEditButton && permissions.update && (
              <Button
                type="link"
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleEdit(record)}
              >
                {editButtonText}
              </Button>
            )}
            
            {/* 默认删除按钮 */}
            {showDeleteButton && permissions.delete && (
              <Popconfirm
                title={typeof deleteConfirmTitle === 'function' ? deleteConfirmTitle(record) : deleteConfirmTitle}
                onConfirm={() => handleDelete((record as any)[rowKey])}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                >
                  {deleteButtonText}
                </Button>
              </Popconfirm>
            )}
          </>
        )}
      </Space>
    ),
  };

  // 处理 columns
  const baseColumns = typeof columns === 'function' ? columns(handlers, context) : columns;
  const finalColumns = showActionColumn ? [...baseColumns, defaultActionColumn] : baseColumns;

  // 处理 formItems - 编辑模式优先使用 editFormItems
  const getFormItems = () => {
    const items = formMode === 'edit' && editFormItems ? editFormItems : formItems;
    return typeof items === 'function' ? items(formMode, currentRecord) : items;
  };
  const finalFormItems = getFormItems();

  return (
    <div>
      <PageHeader
        title={title}
        extra={
          <Space>
            {/* 批量删除按钮 */}
            {enableBatchDelete && batchDeleteApi && permissions.delete && (
              <Popconfirm
                title={`确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`}
                onConfirm={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  disabled={selectedRowKeys.length === 0}
                >
                  {batchDeleteButtonText} ({selectedRowKeys.length})
                </Button>
              </Popconfirm>
            )}
            
            {/* 导入导出功能 */}
            {(exportConfig || importConfig) && (
              <ExportImport
                showExportButton={!!exportConfig}
                exportFilename={exportConfig?.filename}
                exportColumns={exportConfig?.columns}
                exportSheetName={exportConfig?.sheetName}
                onExport={exportConfig?.onExport || (async () => data)}
                
                showImportButton={!!importConfig}
                onImport={importConfig?.onImport}
                validateImportData={importConfig?.validate}
                
                showTemplateButton={!!importConfig}
                templateFilename={importConfig?.templateFilename}
                templateColumns={importConfig?.templateColumns || exportConfig?.columns}
                templateSampleData={importConfig?.templateSampleData}
              />
            )}
            
            {/* 刷新按钮 */}
            <Button 
              icon={<ReloadOutlined />} 
              onClick={refresh}
              loading={loading}
            >
              刷新
            </Button>
            
            {/* 自定义头部操作 */}
            {renderHeaderExtra && renderHeaderExtra(handlers, context)}
            
            {/* 默认新增按钮 */}
            {showCreateButton && permissions.create && (
              <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
                {createButtonText}
              </Button>
            )}
          </Space>
        }
      />

      {/* 搜索表单 */}
      {searchItems && searchItems.length > 0 && (
        <SearchForm
          items={searchItems}
          onSearch={handleSearch}
          onReset={handleReset}
          loading={loading}
        />
      )}

      {/* 数据表格 */}
      <Card>
        <DataTable
          columns={finalColumns}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onPageChange={handlePageChange}
          rowKey={rowKey}
          scroll={scroll}
          rowSelection={enableBatchDelete ? {
            selectedRowKeys,
            onChange: (keys: React.Key[], rows: T[]) => {
              setSelectedRowKeys(keys);
              setSelectedRows(rows);
            },
          } : undefined}
        />
      </Card>

      {/* 标准表单弹窗 */}
      {finalFormItems && finalFormItems.length > 0 && (
        <ModalForm
          visible={formVisible}
          mode={formMode}
          title={formMode === 'create' ? (formTitle.create || '新增') : (formTitle.edit || '编辑')}
          items={finalFormItems}
          initialValues={currentRecord}
          onSubmit={handleFormSubmit}
          onCancel={() => setFormVisible(false)}
          width={formWidth}
        />
      )}

      {/* 详情抽屉 */}
      {renderDetailContent && (
        <Drawer
          title={detailDrawerTitle}
          placement="right"
          width={detailDrawerWidth}
          onClose={() => setDetailDrawerVisible(false)}
          open={detailDrawerVisible}
        >
          {detailRecord && renderDetailContent(detailRecord, handlers, context)}
        </Drawer>
      )}

      {/* 自定义内容（额外的弹窗等） */}
      {children && children(handlers, context)}
    </div>
  );
}

export default CrudPage;
